import { ref, reactive, computed, toRefs } from 'vue';
import { message } from 'ant-design-vue';

/**
 * 表格表单操作相关hook
 * 处理新增、编辑等表单操作
 * @param {Object} options - 配置选项
 * @returns {Object} - 返回表单相关状态和方法
 */
export function useTableForm(options) {
  let {
    defaultForm = {}, // 默认表单数据
    rules = {}, // 表单验证规则
    addApi = null, // 添加数据接口
    updateApi = null, // 更新数据接口
    getDetailApi = null, // 获取详情接口
    transform = null, // 表单数据转换函数
    afterSubmit = null, // 提交后回调
    autoHandleError = true, // 是否自动处理错误
    autoMessage = true, // 是否自动显示消息
    validateOnSubmit = true, // 提交时是否验证表单
  } = options || {};

  // 表单状态
  const formRef = ref(null);
  const formState = reactive({ ...defaultForm });
  const formRules = reactive({ ...rules });
  const submitLoading = ref(false);
  const detailLoading = ref(false);
  const modalVisible = ref(false);
  const drawerVisible = ref(false);
  const formErrors = ref({});
  const isEdit = ref(false);

  // 获取详情
  const getDetail = async (id) => {
    if (!getDetailApi || !id) return null;
    
    detailLoading.value = true;
    try {
      const response = await getDetailApi(id);
      const detailData = response.data;
      
      // 更新表单数据
      Object.keys(formState).forEach((key) => {
        if (detailData[key] !== undefined) {
          formState[key] = detailData[key];
        }
      });
      
      return detailData;
    } catch (err) {
      if (autoHandleError) {
        message.error(err.message || '获取详情失败');
      }
      throw err;
    } finally {
      detailLoading.value = false;
    }
  };

  // 转换表单数据
  const transformFormData = (data) => {
    if (transform && typeof transform === 'function') {
      return transform(data, isEdit.value);
    }
    return data;
  };


  // 提交表单
  const submitForm = async () => {
    submitLoading.value = true;
    try {
      // 转换表单数据
      const submitData = transformFormData({ ...formState });
      console.log(formState,submitData,'submitData1');
      let response;
      if (isEdit.value) {
        // 更新
        if (!updateApi) {
          throw new Error('未提供更新接口');
        }
        response = await updateApi(submitData);
      } else {
        // 新增
        if (!addApi) {
          throw new Error('未提供添加接口');
        }
        response = await addApi(submitData);
      }
      
      // 自动显示消息
      if (autoMessage) {
        message.success(isEdit.value ? '更新成功' : '添加成功');
      }
      
      // 提交后回调
      if (afterSubmit && typeof afterSubmit === 'function') {
        afterSubmit(response, isEdit.value);
      }
      
      // 关闭模态框/抽屉
      closeForm();
      
      return response;
    } catch (err) {
      if (autoHandleError) {
        message.error(err.message || (isEdit.value ? '更新失败' : '添加失败'));
      }
      throw err;
    } finally {
      submitLoading.value = false;
    }
  };

  // 打开表单
  const openForm = (record = null, type = 'modal') => {
    console.log(formState,'formStateOpenForm');
    // 重置表单
    resetForm();
    
    // 设置编辑状态
    isEdit.value = !!record;
    
    // 如果是编辑模式，填充表单
    if (record) {
      Object.keys(record).forEach((key) => {
        if (record[key] !== undefined) {
          formState[key] = record[key];
        }
      });
    }
    
    // 打开模态框/抽屉
    if (type === 'drawer') {
      drawerVisible.value = true;
    } else {
      modalVisible.value = true;
    }
  };

  // 关闭表单
  const closeForm = () => {
    modalVisible.value = false;
    drawerVisible.value = false;
  };

  // 重置表单
  const resetForm = () => {
    if (formRef.value) {
      formRef.value.resetFields();
    }
    
    // 手动重置
    Object.keys(formState).forEach((key) => {
      formState[key] = defaultForm[key] !== undefined ? defaultForm[key] : undefined;
    });
    
    formErrors.value = {};
    isEdit.value = false;
  };

  return {
    // 状态
    formRef,
    formState,
    formRules,
    formErrors,
    submitLoading,
    detailLoading,
    modalVisible,
    drawerVisible,
    isEdit,
    
    // 计算属性
    modalTitle: computed(() => isEdit.value ? '编辑' : '新增'),
    
    // 方法
    submitForm,
    openForm,
    closeForm,
    resetForm,
    getDetail,
  };
}
